package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import java.io.OutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class Router {

    public void route(Parameter request, OutputStream response) {
        Config config = Config.getInstance();
// TODO: [222024321072050/邓琳馨]根据请求的URL获取Handler
        // 根据请求的URL获取Handler
        Handler handler = config.getHandler(request.getUrl());

        if (handler == null) {
            // 如果没有匹配的路由，使用 DefaultHandler 处理
            handler = config.getHandler("/");
            System.out.println("未找到匹配的处理器，使用默认处理器处理: " + request.getUrl());
        }

        if (handler != null) {
            try {
                System.out.println("使用处理器: " + handler.getClass().getSimpleName() + " 处理请求: " + request.getMethod() + " " + request.getUrl());
                handler.handle(request, response);
            } catch (Exception e) {
                System.err.println("处理器执行异常: " + e.getMessage());
                e.printStackTrace();
                sendErrorResponse(500, "Internal Server Error - Handler Execution Failed", response);
            }
        } else {
            // 如果连DefaultHandler都没有，返回500 Internal Server Error
            System.err.println("严重错误: 默认处理器未配置");
            sendErrorResponse(500, "Internal Server Error - Default Handler Not Configured", response);
        }
    }

    /**
     * 发送HTTP错误响应
     */
    private void sendErrorResponse(int statusCode, String message, OutputStream response) {
        // TODO: [222024321072050/邓琳馨]如果连DefaultHandler都没有，返回500 Internal Server Error
        try {
            String statusText = getStatusText(statusCode);
            String htmlContent = generateErrorHtml(statusCode, statusText, message);

            String httpResponse = "HTTP/1.1 " + statusCode + " " + statusText + "\r\n" +
                    "Content-Type: text/html; charset=utf-8\r\n" +
                    "Content-Length: " + htmlContent.getBytes(StandardCharsets.UTF_8).length + "\r\n" +
                    "Connection: close\r\n" +
                    "\r\n" +
                    htmlContent;

            response.write(httpResponse.getBytes(StandardCharsets.UTF_8));
            response.flush();

            System.out.println("发送错误响应: " + statusCode + " " + statusText);

        } catch (IOException e) {
            System.err.println("发送错误响应时发生IO异常: " + e.getMessage());
        }
    }

    /**
     * 生成错误页面的HTML内容
     */
    private String generateErrorHtml(int statusCode, String statusText, String message) {
        return "<!DOCTYPE html>\n" +
                "<html lang=\"zh-CN\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
                "    <title>" + statusCode + " " + statusText + "</title>\n" +
                "    <style>\n" +
                "        body { font-family: Arial, sans-serif; margin: 40px; line-height: 1.6; }\n" +
                "        .error-container { max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px; }\n" +
                "        .error-code { color: #d9534f; font-size: 2em; margin-bottom: 10px; }\n" +
                "        .error-message { color: #333; font-size: 1.2em; margin-bottom: 20px; }\n" +
                "        .error-details { background: #f9f9f9; padding: 15px; border-radius: 3px; font-size: 0.9em; }\n" +
                "        .footer { margin-top: 20px; font-size: 0.8em; color: #666; text-align: center; }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "    <div class=\"error-container\">\n" +
                "        <div class=\"error-code\">" + statusCode + " " + statusText + "</div>\n" +
                "        <div class=\"error-message\">" + escapeHtml(message) + "</div>\n" +
                "        <div class=\"error-details\">\n" +
                "            <p>抱歉，服务器在处理您的请求时遇到了问题。</p>\n" +
                "            <p>请稍后重试，或联系网站管理员。</p>\n" +
                "        </div>\n" +
                "        <div class=\"footer\">\n" +
                "            MiniWebSvr - 轻量级Java Web服务器\n" +
                "        </div>\n" +
                "    </div>\n" +
                "</body>\n" +
                "</html>";
    }

    /**
     * HTML转义，防止XSS攻击
     */
    private String escapeHtml(String text) {
        if (text == null) return "";
        return text.replace("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace("\"", "&quot;")
                .replace("'", "&#39;");
    }

    /**
     * 获取HTTP状态码对应的文本描述
     */
    private String getStatusText(int statusCode) {
        switch (statusCode) {
            case 400: return "Bad Request";
            case 404: return "Not Found";
            case 405: return "Method Not Allowed";
            case 500: return "Internal Server Error";
            case 501: return "Not Implemented";
            case 503: return "Service Unavailable";
            default: return "Unknown Error";
        }
    }

    /**
     * 发送404 Not Found错误响应（可用于其他需要404的地方）
     */
    public void sendNotFound(Parameter request, OutputStream response) {
        String message = "请求的资源 '" + request.getUrl() + "' 未找到";
        sendErrorResponse(404, message, response);
    }

    /**
     * 发送405 Method Not Allowed错误响应
     */
    public void sendMethodNotAllowed(Parameter request, OutputStream response) {
        String message = "请求方法 '" + request.getMethod() + "' 不被支持";
        sendErrorResponse(405, message, response);
    }
}